#coding=utf-8
#Boa:Dialog:DlgPayment

import wx
from config import *
from product import *
from ctrlAider import *
from myLogger import *

def create(parent):
    return DlgPayment(parent)

[wxID_DLGPAYMENT, wxID_DLGPAYMENTBTNCANCEL, wxID_DLGPAYMENTBTNOK, 
 wxID_DLGPAYMENTCBPAYWAY, wxID_DLGPAYMENTCBSTAFF, wxID_DLGPAYMENTDATEBILL, 
 wxID_DLGPAYMENTTCDEBT, wxID_DLGPAYMENTTCMEMO, wxID_DLGPAYMENTTCMONEY, 
 wxID_DLGPAYMENTTCORDERID, wxID_DLGPAYMENTTCPARTNER, wxID_DLGPAYMENTTCSALEID, 
 wxID_DLGPAYMENTTDATE, wxID_DLGPAYMENTTDEBT, wxID_DLGPAYMENTTMEMO, 
 wxID_DLGPAYMENTTMONEY, wxID_DLGPAYMENTTORDERID, wxID_DLGPAYMENTTPARTNER, 
 wxID_DLGPAYMENTTPAYWAY, wxID_DLGPAYMENTTSALEID, wxID_DLGPAYMENTTSTAFF, 
] = [wx.NewId() for _init_ctrls in range(21)]

class DlgPayment(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DLGPAYMENT, name=u'DlgPayment',
              parent=prnt, pos=wx.Point(461, 212), size=wx.Size(705, 466),
              style=wx.DEFAULT_DIALOG_STYLE, title=u'\u4f1a\u6b3e\u5355')
        self.SetClientSize(wx.Size(697, 432))
        self.Center(wx.BOTH)
        self.SetWindowVariant(wx.WINDOW_VARIANT_LARGE)
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.tPartner = wx.StaticText(id=wxID_DLGPAYMENTTPARTNER,
              label=u'\u5ba2\u6237\uff1a', name=u'tPartner', parent=self,
              pos=wx.Point(88, 80), size=wx.Size(64, 14), style=0)

        self.tcPartner = wx.TextCtrl(id=wxID_DLGPAYMENTTCPARTNER,
              name=u'tcPartner', parent=self, pos=wx.Point(160, 72),
              size=wx.Size(200, 22), style=0, value=u'')

        self.tPayWay = wx.StaticText(id=wxID_DLGPAYMENTTPAYWAY,
              label=u'\u6536\u6b3e\u65b9\u5f0f\uff1a', name=u'tPayWay',
              parent=self, pos=wx.Point(376, 176), size=wx.Size(85, 16),
              style=0)

        self.cbPayWay = wx.ComboBox(choices=[], id=wxID_DLGPAYMENTCBPAYWAY,
              name=u'cbPayWay', parent=self, pos=wx.Point(464, 168),
              size=wx.Size(130, 24), style=0, value=u'')
        self.cbPayWay.SetLabel(u'')

        self.tMoney = wx.StaticText(id=wxID_DLGPAYMENTTMONEY,
              label=u'\u6536\u6b3e\u91d1\u989d\uff1a', name=u'tMoney',
              parent=self, pos=wx.Point(88, 176), size=wx.Size(85, 16),
              style=0)

        self.tcMoney = wx.TextCtrl(id=wxID_DLGPAYMENTTCMONEY, name=u'tcMoney',
              parent=self, pos=wx.Point(176, 168), size=wx.Size(104, 22),
              style=0, value=u'')

        self.tOrderId = wx.StaticText(id=wxID_DLGPAYMENTTORDERID,
              label=u'\u5355\u53f7\uff1a', name=u'tOrderId', parent=self,
              pos=wx.Point(376, 80), size=wx.Size(64, 14), style=0)

        self.tDate = wx.StaticText(id=wxID_DLGPAYMENTTDATE,
              label=u'\u65e5\u671f\uff1a', name=u'tDate', parent=self,
              pos=wx.Point(376, 128), size=wx.Size(64, 14), style=0)

        self.dateBill = wx.DatePickerCtrl(id=wxID_DLGPAYMENTDATEBILL,
              name=u'dateBill', parent=self, pos=wx.Point(464, 120),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateBill.SetLabel(u'2013-11-27')
        self.dateBill.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateBill.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateBill.Bind(wx.EVT_DATE_CHANGED, self.OnDateBillDateChanged,
              id=wxID_DLGPAYMENTDATEBILL)

        self.tStaff = wx.StaticText(id=wxID_DLGPAYMENTTSTAFF,
              label=u'\u7ecf\u529e\u4eba\uff1a', name=u'tStaff', parent=self,
              pos=wx.Point(376, 224), size=wx.Size(72, 14), style=0)

        self.cbStaff = wx.ComboBox(choices=[], id=wxID_DLGPAYMENTCBSTAFF,
              name=u'cbStaff', parent=self, pos=wx.Point(464, 216),
              size=wx.Size(130, 24), style=0, value=u'')

        self.btnOK = wx.Button(id=wxID_DLGPAYMENTBTNOK, label=u'\u786e\u5b9a',
              name=u'btnOK', parent=self, pos=wx.Point(232, 352),
              size=wx.Size(75, 24), style=0)
        self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton,
              id=wxID_DLGPAYMENTBTNOK)

        self.btnCancel = wx.Button(id=wxID_DLGPAYMENTBTNCANCEL,
              label=u'\u53d6\u6d88', name=u'btnCancel', parent=self,
              pos=wx.Point(368, 352), size=wx.Size(75, 24), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_DLGPAYMENTBTNCANCEL)

        self.tMemo = wx.StaticText(id=wxID_DLGPAYMENTTMEMO,
              label=u'\u5907\u6ce8\uff1a', name=u'tMemo', parent=self,
              pos=wx.Point(88, 280), size=wx.Size(56, 14), style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_DLGPAYMENTTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(184, 272), size=wx.Size(384, 24),
              style=0, value=u'')

        self.tcOrderId = wx.StaticText(id=wxID_DLGPAYMENTTCORDERID,
              label=u'P(GK)F-20140516-0001', name=u'tcOrderId', parent=self,
              pos=wx.Point(464, 80), size=wx.Size(180, 16), style=0)

        self.tDebt = wx.StaticText(id=wxID_DLGPAYMENTTDEBT,
              label=u'\u6b20\u6b3e\u91d1\u989d\uff1a', name=u'tDebt',
              parent=self, pos=wx.Point(88, 128), size=wx.Size(85, 16),
              style=0)

        self.tcDebt = wx.StaticText(id=wxID_DLGPAYMENTTCDEBT, label=u'0',
              name=u'tcDebt', parent=self, pos=wx.Point(176, 128),
              size=wx.Size(104, 16), style=0)

        self.tSaleId = wx.StaticText(id=wxID_DLGPAYMENTTSALEID,
              label=u'\u9500\u552e\u5355\u53f7\uff1a', name=u'tSaleId',
              parent=self, pos=wx.Point(376, 40), size=wx.Size(85, 16),
              style=0)

        self.tcSaleId = wx.StaticText(id=wxID_DLGPAYMENTTCSALEID, label=u'XS-',
              name=u'tcSaleId', parent=self, pos=wx.Point(464, 40),
              size=wx.Size(27, 16), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)

        self.myInit()
    
    def myInit(self):
        #self.SetSize(Cfg.getDlgAreaSize())
        #self.Move(Cfg.getDlgAreaPos())
        self.SetFont(Cfg.getFrameFont())
        self.SetBackgroundColour(Cfg.getFrameBgColor())
        

        self.dateBill.SetValue(wx.DateTime.Today())
        self.refreshId()
        
        self.cb = MyComboBoxDecorator(self.cbPayWay, CDataAccount, CDataAccount.COL_BRIEFNAME)
        self.cb.refresh()
        self.cb.SetValue(CDataAccount.getDefAccount())
        
        self.cbHandler = MyComboBoxDecorator(self.cbStaff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(Cfg.getCurUser().getValue(CDataStaff.COL_NAME))
        
        self.initState()
    
    def initState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW
        
        self.preVoucherId = ''
        
    def getMoney(self):
        return float(self.tcMoney.GetValue())
    
    def refreshId(self):
        date = self.dateBill.GetValue().Format('%Y%m%d')
        self.tcOrderId.SetLabel(CDataVoucher.newBillId(date))
        
    def setCustData(self, custObj, debt=-1, saleOrderId=''):
        self.custObj = custObj
        name = self.custObj.getFieldVal(index = CDataCustomer.COL_NAME)
        self.tcPartner.SetValue(name)  
        
        if (saleOrderId == ''):
            self.tcSaleId.Show(False)
            self.tSaleId.Show(False)
        else:
            self.tcSaleId.SetLabel(saleOrderId)
        
        if (debt == -1):
            debt = custObj.getDebt()
        self.tcDebt.SetLabel(str(debt))
        self.tcMoney.SetValue(str(debt))

        #需要在显示时设置，而不是初始化
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
        
    def setVoucherData(self, voucherId):
        '''修改已经存在的收款单，保存到数据库是要用update(del->insert,因为id可能变化
        '''
        self.curState = self.STATE_MODIFY
        self.preVoucherId = voucherId
            
        voucherObj = CDataVoucher.getFirstInstance({CDataVoucher.COL_ID:voucherId})
        
        custId = voucherObj.getValue(CDataVoucher.COL_PEERID)
        custObj = CDataCustomer.getFirstInstance({CDataCustomer.COL_ID:custId})
        self.custObj = custObj
        custName = custObj.getValue(CDataCustomer.COL_NAME)
        
        hId = voucherObj.getValue(CDataVoucher.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        hName = hObj.getValue(CDataStaff.COL_NAME)
        #rId = voucherObj.getValue(CDataVoucher.COL_RECORDERID)
        
        money = voucherObj.getValue(CDataVoucher.COL_MONEY)
        memo = voucherObj.getValue(CDataVoucher.COL_MEMO)
        date = voucherObj.getValue(CDataVoucher.COL_DATE)
        accountId = voucherObj.getValue(CDataVoucher.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        accountName = accountObj.getValue(CDataAccount.COL_BRIEFNAME)
        
        
        if (isinstance(date, str) or isinstance(date, unicode)):
            #print type(date)
            #import time
            import datetime
            #t = time.strptime(date, '%Y-%m-%d')
            #date = datetime.datetime(t[:6])
            date = datetime.datetime.strptime(date, '%Y-%m-%d')
            #print type(date)
        dateTime = wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0)
        debt = custObj.getDebt()
        
        #return (voucherId, date, accountName, hName, custName, debt, money, memo)
        
        #show value
        self.tcOrderId.SetLabel(voucherId)
        self.dateBill.SetValue(dateTime)
        self.cb.SetValue(accountName)
        self.cbHandler.SetValue(hName)
        self.tcPartner.SetValue(custName)
        self.tcDebt.SetLabel(str(debt))
        self.tcMoney.SetValue(str(money))
        self.tcMemo.SetValue(memo)
        
        return (debt, money)
    
    def setSaleData(self, saleId):
        soObj = CDataSaleOrder.getFirstInstance({CDataSaleOrder.COL_ID:saleId})
        if (soObj is None):
            logger.info('销售单%s已经被删除', (saleId))
            return (None, None)
        
        #amount = soObj.getValue(CDataSaleOrder.COL_TOTAL)
        amount = soObj.getUnpaid()
        money = amount
        memo = u'为%s收款' %(saleId)
        
        custId = soObj.getValue(CDataSaleOrder.COL_PEERID)
        custObj = CDataCustomer.getFirstInstance({CDataCustomer.COL_ID:custId})
        self.custObj = custObj
        custName = custObj.getValue(CDataCustomer.COL_NAME)
        
        #return (saleId, custName, amount, money, memo)
        
        self.tcSaleId.SetLabel(saleId)
        self.tcPartner.SetValue(custName)
        self.tcDebt.SetLabel(str(amount))
        self.tcMoney.SetValue(str(money))
        self.tcMemo.SetValue(memo)
    
        return (amount, money)
    
    def setData(self, saleId, voucherId = ''):
        '''设置收款单需要的一些数据
            saleId - 为销售单<saleId>收款
            voucherId - 修改收款单信息，可选
        '''
        if (saleId == ''):
            #没有指定销售单，或原来关联了多个销售单，由于未对此进行设计，
            #所以修改后订单并不关联销售单
            if (voucherId == ''):
                logger.error('saleId and voucherId cannot be empty all at once')
                return
            
            self.tcSaleId.Show(False)
            self.tSaleId.Show(False)

            self.setVoucherData(voucherId)
        else:
            amount,money = self.setSaleData(saleId)

            if(voucherId != ''):
                debt,money = self.setVoucherData(voucherId)
                
                #既有saleId又有voucherId，则欠款为sale，收款为voucher
                if (amount is None):
                    self.tcSaleId.Show(False)
                    self.tSaleId.Show(False)
                    self.tcDebt.SetLabel(str(debt))
                else:
                    self.tcDebt.SetLabel(str(amount))
                self.tcMoney.SetValue(str(money))
    
        #需要在显示时设置，而不是初始化
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
            
    def saveVoucherToDB(self):
        id = self.tcOrderId.GetLabel()
        custId = self.custObj.getFieldVal(index = CDataCustomer.COL_ID)
        
        accountObj = self.cb.getSelectObj()
        accountId = accountObj.getValue(CDataAccount.COL_ID)
        
        money = float(self.tcMoney.GetValue())
        date = self.dateBill.GetValue().Format('%Y-%m-%d') 
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderID = Cfg.getCurUser().getValue(CDataStaff.COL_ID)      
        memo = self.tcMemo.GetValue()
        
        data = {CDataVoucher.COL_ID:id, 
                CDataVoucher.COL_PEERID:custId, 
                CDataVoucher.COL_ACCOUNTID:accountId,
                CDataVoucher.COL_MONEY:money, 
                CDataVoucher.COL_DATE:date, 
                CDataVoucher.COL_HANDLERID:handlerId,
                CDataVoucher.COL_RECORDERID:recorderID, 
                CDataVoucher.COL_MEMO:memo}
        obj = CDataVoucher.factory()
        obj.setMulFieldVal(data)
        obj.insert()
    
    def saveFundCustToDB(self):
        voucherId =  self.tcOrderId.GetLabel()
        saleOrderId =  self.tcSaleId.GetLabel()
        
        data = {CRelFundCustomer.COL_BILLID:saleOrderId, 
                CRelFundCustomer.COL_VOUCHERID:voucherId, 
                CRelFundCustomer.COL_MONEY:self.getMoney()}
        obj = CRelFundCustomer.factory()
        obj.setMulFieldVal(data)
        obj.insert()

    def deleteVoucher(self, voucherId):
        CDataVoucher.delData({CDataVoucher.COL_ID:voucherId})
    
    def deleteFundCust(self, voucherId):
        CRelFundCustomer.delData({CRelFundCustomer.COL_VOUCHERID:voucherId})
    
    def delOldData(self, voucherId):
        self.deleteFundCust(voucherId)
        self.deleteVoucher(voucherId)

    def OnDateBillDateChanged(self, event):
        self.refreshId()

    def OnBtnOKButton(self, event):
        
        if (self.getMoney() <= 0.0):
##            dlg = wx.MessageDialog(self, u'未收款？收款金额为0',
##                                    u'提示', wx.YES_NO|wx.ICON_QUESTION)
##            if (dlg.ShowModal() == wx.ID_YES):
##                #退出，但不保存收款单
##                self.EndModal(wx.ID_OK)
            dlg = wx.MessageDialog(self, u'收款金额无效，请重新输入',
                                    u'提示', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
##        amount = float(self.tcDebt.GetLabel())
##        discount = amount - self.getMoney()
##        if (discount >= 0):
##            dlg = wx.MessageDialog(self, u'是否优惠金额',
##                                    u'提示', wx.OK|wx.ICON_INFORMATION)
##            dlg.ShowModal()
##            return
            
                
        if(self.curState == self.STATE_MODIFY and self.preVoucherId != ''):
            self.delOldData(self.preVoucherId)
            
        self.saveVoucherToDB()
        if (self.tSaleId.IsShown()):
            self.saveFundCustToDB()
            
        if (self.IsModal()):
            self.EndModal(wx.ID_OK)
        else:
            self.Close()

    def OnBtnCancelButton(self, event):
        if (self.IsModal()):
            self.EndModal(wx.ID_CANCEL)
        else:
            self.Close()
        
